import { InfluxDB, Point } from '@influxdata/influxdb-client'
import axios from 'axios'
import logger from './logger'

class InfluxDBService {
  constructor() {
    this.connections = new Map()
    this.currentConnection = null
    this.cache = new Map() // 查询缓存
    this.cacheMaxSize = 50 // 最大缓存条目数
    this.cacheMaxAge = 5 * 60 * 1000 // 缓存过期时间 5分钟
    this.axiosInstances = new Map() // Axios 实例池
    this.requestTimeouts = new Map() // 请求超时控制器
    this.defaultTimeout = 30000 // 默认超时 30秒

    // 定期清理过期缓存
    this._startCacheCleanup()
  }

  /**
   * 启动缓存清理定时器
   * @private
   */
  _startCacheCleanup() {
    setInterval(() => {
      const now = Date.now()
      let cleanedCount = 0

      for (const [key, entry] of this.cache.entries()) {
        if (now - entry.timestamp > this.cacheMaxAge) {
          this.cache.delete(key)
          cleanedCount++
        }
      }

      if (cleanedCount > 0) {
        logger.logCache('CLEANUP', `Removed ${cleanedCount} expired entries`)
      }
    }, 60000) // 每分钟检查一次
  }

  /**
   * 获取或创建 Axios 实例
   * @private
   */
  _getAxiosInstance(connectionId, baseURL) {
    if (!this.axiosInstances.has(connectionId)) {
      const instance = axios.create({
        baseURL,
        timeout: this.defaultTimeout,
        headers: {
          'Content-Type': 'application/json'
        }
      })

      // 请求拦截器 - 记录请求开始
      instance.interceptors.request.use(config => {
        config.metadata = { startTime: performance.now() }
        logger.debug('HTTP', `${config.method.toUpperCase()} ${config.url}`)
        return config
      })

      // 响应拦截器 - 记录响应和性能
      instance.interceptors.response.use(
        response => {
          const duration = performance.now() - response.config.metadata.startTime
          logger.logApiRequest(
            response.config.method.toUpperCase(),
            response.config.url,
            response.status,
            duration
          )
          return response
        },
        error => {
          if (error.config && error.config.metadata) {
            const duration = performance.now() - error.config.metadata.startTime
            logger.logApiRequest(
              error.config.method.toUpperCase(),
              error.config.url,
              error.response?.status || 0,
              duration
            )
          }
          logger.error('HTTP', `Request failed: ${error.config?.url}`, error)
          return Promise.reject(error)
        }
      )

      this.axiosInstances.set(connectionId, instance)
      logger.debug('CONNECTION', `Created axios instance for connection: ${connectionId}`)
    }

    return this.axiosInstances.get(connectionId)
  }

  /**
   * 生成缓存键
   * @private
   */
  _getCacheKey(operation, params) {
    return `${operation}:${JSON.stringify(params)}`
  }

  /**
   * 从缓存获取数据
   * @private
   */
  _getFromCache(key) {
    const entry = this.cache.get(key)
    if (!entry) {
      logger.logCache('MISS', key)
      return null
    }

    const now = Date.now()
    if (now - entry.timestamp > this.cacheMaxAge) {
      this.cache.delete(key)
      logger.logCache('EXPIRED', key)
      return null
    }

    logger.logCache('HIT', key, { age: `${((now - entry.timestamp) / 1000).toFixed(1)}s` })
    return entry.data
  }

  /**
   * 保存到缓存
   * @private
   */
  _saveToCache(key, data) {
    // 如果缓存已满，删除最旧的条目
    if (this.cache.size >= this.cacheMaxSize) {
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
      logger.logCache('EVICT', firstKey, { reason: 'cache full' })
    }

    this.cache.set(key, {
      data,
      timestamp: Date.now()
    })
    logger.logCache('SET', key)
  }

  /**
   * 清除连接相关的缓存
   * @private
   */
  _clearConnectionCache(connectionId) {
    let clearedCount = 0
    for (const key of this.cache.keys()) {
      if (key.includes(connectionId)) {
        this.cache.delete(key)
        clearedCount++
      }
    }
    if (clearedCount > 0) {
      logger.logCache('CLEAR', `Cleared ${clearedCount} entries for connection: ${connectionId}`)
    }
  }

  createConnection(config) {
    const { id, url, token, org, bucket, database, username, password, queryType = 'influxql' } = config

    logger.info('CONNECTION', `Creating connection: ${id}`, { queryType, url })

    const connection = {
      id,
      config: { ...config, queryType },
      client: null,
      queryApi: null,
      writeApi: null
    }

    // For InfluxDB 2.x with Flux
    if (queryType === 'flux' && token) {
      const client = new InfluxDB({ url, token })
      connection.client = client
      connection.queryApi = client.getQueryApi(org)
      connection.writeApi = client.getWriteApi(org, bucket)
    }

    this.connections.set(id, connection)
    logger.debug('CONNECTION', `Connection created successfully: ${id}`)
    return connection
  }

  setCurrentConnection(id) {
    if (this.connections.has(id)) {
      this.currentConnection = this.connections.get(id)
      logger.info('CONNECTION', `Set current connection: ${id}`)
      return true
    }
    logger.warn('CONNECTION', `Connection not found: ${id}`)
    return false
  }

  getCurrentConnection() {
    return this.currentConnection
  }

  async testConnection(config) {
    const perfId = `test_connection_${Date.now()}`
    logger.startPerformance(perfId)
    logger.info('CONNECTION', 'Testing connection', { url: config.url, queryType: config.queryType })

    try {
      const { url, token, org, database, username, password, queryType = 'influxql' } = config

      // First try a simple ping
      try {
        const headers = {}
        if (token) {
          headers['Authorization'] = `Token ${token}`
        }

        const response = await axios.get(`${url}/ping`, {
          headers,
          timeout: 5000
        })

        if (response.status !== 204) {
          throw new Error('Invalid response from InfluxDB server')
        }
        logger.debug('CONNECTION', 'Ping successful')
      } catch (pingError) {
        logger.warn('CONNECTION', 'Ping failed, trying alternate connection test', { error: pingError.message })
      }

      // Test based on query type
      let result
      if (queryType === 'influxql') {
        result = await this.testInfluxQLConnection(config)
      } else if (queryType === 'flux') {
        result = await this.testFluxConnection(config)
      } else {
        result = { success: true, message: 'Connection successful' }
      }

      logger.endPerformance(perfId, { success: result.success })
      return result
    } catch (error) {
      logger.endPerformance(perfId, { success: false })
      logger.error('CONNECTION', 'Connection test failed', error)
      return { success: false, message: error.message }
    }
  }

  async testFluxConnection(config) {
    try {
      const { url, token, org } = config
      
      if (!token) {
        return { success: false, message: 'Token is required for Flux queries' }
      }
      
      const client = new InfluxDB({ url, token })
      const queryApi = client.getQueryApi(org)
      const query = 'buckets() |> limit(n:1)'
      
      await this.executeFluxQuery(queryApi, query)
      return { success: true, message: 'Connection successful (Flux)' }
    } catch (error) {
      if (error.message && error.message.includes('flux-enabled')) {
        return { 
          success: false, 
          message: 'Flux is disabled. Please use InfluxQL query type or enable Flux in InfluxDB config.' 
        }
      }
      return { success: false, message: error.message }
    }
  }

  async testInfluxQLConnection(config) {
    try {
      const { url, database, username, password, token } = config
      
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }
      
      const params = {
        q: 'SHOW DATABASES'
      }
      
      if (database) {
        params.db = database
      }
      
      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }
      
      const response = await axios.get(`${url}/query`, {
        params,
        headers,
        ...authConfig,
        timeout: 5000
      })
      
      if (response.data && response.data.results) {
        return { success: true, message: 'Connection successful (InfluxQL)' }
      }
      
      throw new Error('Invalid response from InfluxDB')
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  async executeFluxQuery(queryApi, query) {
    return new Promise((resolve, reject) => {
      const rows = []
      
      queryApi.queryRows(query, {
        next(row, tableMeta) {
          const o = tableMeta.toObject(row)
          rows.push(o)
        },
        error(error) {
          reject(error)
        },
        complete() {
          resolve(rows)
        }
      })
    })
  }

  async executeInfluxQLQuery(query, database) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const perfId = `influxql_query_${Date.now()}`
    logger.startPerformance(perfId)

    const { id, url, token, username, password } = this.currentConnection.config

    // 检查缓存
    const cacheKey = this._getCacheKey('influxql', { connectionId: id, query, database })
    const cachedResult = this._getFromCache(cacheKey)
    if (cachedResult) {
      logger.endPerformance(perfId, { source: 'cache', rowCount: cachedResult.length })
      return cachedResult
    }

    const headers = {}
    if (token) {
      headers['Authorization'] = `Token ${token}`
    }

    const params = {
      q: query
    }

    // Only add database parameter if provided
    if (database) {
      params.db = database
    }

    const authConfig = {}
    if (username && password) {
      authConfig.auth = { username, password }
    }

    try {
      const axiosInstance = this._getAxiosInstance(id, url)
      const response = await axiosInstance.get('/query', {
        params,
        headers,
        ...authConfig
      })

      if (response.data && response.data.results) {
        const results = []
        const startTransform = performance.now()

        response.data.results.forEach(result => {
          // Check for errors in the result
          if (result.error) {
            throw new Error(result.error)
          }

          if (result.series) {
            result.series.forEach(serie => {
              const { name, columns, values, tags } = serie
              if (values && values.length > 0) {
                // 优化：预分配对象并减少循环嵌套
                values.forEach(value => {
                  const row = {}
                  // 使用 for 循环代替 forEach 提高性能
                  for (let i = 0; i < columns.length; i++) {
                    row[columns[i]] = value[i]
                  }
                  if (tags) {
                    Object.assign(row, tags)
                  }
                  if (name) {
                    row._measurement = name
                  }
                  results.push(row)
                })
              }
            })
          }
        })

        const transformDuration = performance.now() - startTransform
        logger.debug('TRANSFORM', `Data transformation completed in ${transformDuration.toFixed(2)}ms`)

        // 缓存结果（仅缓存 SELECT 查询）
        if (query.trim().toUpperCase().startsWith('SELECT')) {
          this._saveToCache(cacheKey, results)
        }

        const metrics = logger.endPerformance(perfId, {
          source: 'database',
          rowCount: results.length,
          transformTime: `${transformDuration.toFixed(2)}ms`
        })

        if (metrics) {
          logger.logQuery('InfluxQL', query, results.length, parseFloat(metrics.duration))
        }

        return results
      }

      logger.endPerformance(perfId, { source: 'database', rowCount: 0 })
      return []
    } catch (error) {
      logger.endPerformance(perfId, { source: 'database', error: true })
      logger.error('QUERY', 'InfluxQL query failed', error)
      throw error
    }
  }

  async query(query) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }
    
    const { queryType } = this.currentConnection.config
    
    if (queryType === 'flux') {
      if (!this.currentConnection.queryApi) {
        throw new Error('Flux queries not supported. Please use InfluxQL.')
      }
      return await this.executeFluxQuery(this.currentConnection.queryApi, query)
    } else {
      return await this.executeInfluxQLQuery(query)
    }
  }

  async getMeasurements() {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const { id, queryType, bucket, database } = this.currentConnection.config

    // 检查缓存
    const cacheKey = this._getCacheKey('measurements', { connectionId: id, bucket, database })
    const cachedResult = this._getFromCache(cacheKey)
    if (cachedResult) {
      return cachedResult
    }

    logger.debug('METADATA', 'Fetching measurements', { queryType, bucket, database })

    let results
    if (queryType === 'flux') {
      const query = `
        import "influxdata/influxdb/schema"
        schema.measurements(bucket: "${bucket}")
      `
      results = await this.query(query)
    } else {
      const query = 'SHOW MEASUREMENTS'
      const queryResults = await this.executeInfluxQLQuery(query, database)
      results = queryResults.map(r => ({ _value: r.name }))
    }

    // 缓存结果
    this._saveToCache(cacheKey, results)
    logger.info('METADATA', `Fetched ${results.length} measurements`)

    return results
  }

  async getFields(measurement) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const { id, queryType, bucket, database } = this.currentConnection.config

    // 检查缓存
    const cacheKey = this._getCacheKey('fields', { connectionId: id, bucket, database, measurement })
    const cachedResult = this._getFromCache(cacheKey)
    if (cachedResult) {
      return cachedResult
    }

    logger.debug('METADATA', `Fetching fields for measurement: ${measurement}`)

    let results
    if (queryType === 'flux') {
      const query = `
        import "influxdata/influxdb/schema"
        schema.measurementFieldKeys(
          bucket: "${bucket}",
          measurement: "${measurement}"
        )
      `
      results = await this.query(query)
    } else {
      const query = `SHOW FIELD KEYS FROM "${measurement}"`
      const queryResults = await this.executeInfluxQLQuery(query, database)
      results = queryResults.map(r => ({ _value: r.fieldKey }))
    }

    // 缓存结果
    this._saveToCache(cacheKey, results)
    logger.info('METADATA', `Fetched ${results.length} fields for ${measurement}`)

    return results
  }

  async getTags(measurement) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const { id, queryType, bucket, database } = this.currentConnection.config

    // 检查缓存
    const cacheKey = this._getCacheKey('tags', { connectionId: id, bucket, database, measurement })
    const cachedResult = this._getFromCache(cacheKey)
    if (cachedResult) {
      return cachedResult
    }

    logger.debug('METADATA', `Fetching tags for measurement: ${measurement}`)

    let results
    if (queryType === 'flux') {
      const query = `
        import "influxdata/influxdb/schema"
        schema.measurementTagKeys(
          bucket: "${bucket}",
          measurement: "${measurement}"
        )
      `
      results = await this.query(query)
    } else {
      const query = `SHOW TAG KEYS FROM "${measurement}"`
      const queryResults = await this.executeInfluxQLQuery(query, database)
      results = queryResults.map(r => ({ _value: r.tagKey }))
    }

    // 缓存结果
    this._saveToCache(cacheKey, results)
    logger.info('METADATA', `Fetched ${results.length} tags for ${measurement}`)

    return results
  }

  async writeData(measurement, tags, fields, timestamp = null) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const perfId = `write_data_${Date.now()}`
    logger.startPerformance(perfId)
    logger.info('WRITE', `Writing data to measurement: ${measurement}`, { tags, fields })

    const { id, queryType, url, token, database, username, password } = this.currentConnection.config

    try {
      if (queryType === 'flux' && this.currentConnection.writeApi) {
        const point = new Point(measurement)

        Object.entries(tags).forEach(([key, value]) => {
          point.tag(key, value)
        })

        Object.entries(fields).forEach(([key, value]) => {
          if (typeof value === 'number') {
            point.floatField(key, value)
          } else if (typeof value === 'boolean') {
            point.booleanField(key, value)
          } else {
            point.stringField(key, String(value))
          }
        })

        if (timestamp) {
          point.timestamp(timestamp)
        }

        this.currentConnection.writeApi.writePoint(point)
        await this.currentConnection.writeApi.close()

        // Recreate write API for next use
        this.currentConnection.writeApi = this.currentConnection.client.getWriteApi(
          this.currentConnection.config.org,
          this.currentConnection.config.bucket
        )

        logger.endPerformance(perfId, { queryType: 'flux', measurement })
      } else {
        // Use InfluxQL write endpoint
        let lineProtocol = measurement

        // Add tags
        const tagPairs = Object.entries(tags).map(([k, v]) => `${k}=${v}`)
        if (tagPairs.length > 0) {
          lineProtocol += ',' + tagPairs.join(',')
        }

        // Add fields
        lineProtocol += ' '
        const fieldPairs = Object.entries(fields).map(([k, v]) => {
          if (typeof v === 'string') {
            return `${k}="${v}"`
          }
          return `${k}=${v}`
        })
        lineProtocol += fieldPairs.join(',')

        // Add timestamp
        if (timestamp) {
          lineProtocol += ` ${timestamp}`
        }

        const headers = {
          'Content-Type': 'text/plain'
        }
        if (token) {
          headers['Authorization'] = `Token ${token}`
        }

        const authConfig = {}
        if (username && password) {
          authConfig.auth = { username, password }
        }

        const axiosInstance = this._getAxiosInstance(id, url)
        await axiosInstance.post('/write', lineProtocol, {
          params: { db: database },
          headers,
          ...authConfig
        })

        logger.endPerformance(perfId, { queryType: 'influxql', measurement })
      }

      // 清除相关缓存（写入后元数据可能变化）
      this._clearConnectionCache(id)
      logger.info('WRITE', `Successfully wrote data to ${measurement}`)

      return true
    } catch (error) {
      logger.endPerformance(perfId, { error: true })
      logger.error('WRITE', `Failed to write data to ${measurement}`, error)
      throw error
    }
  }

  removeConnection(id) {
    logger.info('CONNECTION', `Removing connection: ${id}`)

    if (this.currentConnection && this.currentConnection.id === id) {
      this.currentConnection = null
    }

    // 清除相关缓存
    this._clearConnectionCache(id)

    // 清除 axios 实例
    if (this.axiosInstances.has(id)) {
      this.axiosInstances.delete(id)
      logger.debug('CONNECTION', `Removed axios instance for connection: ${id}`)
    }

    const result = this.connections.delete(id)
    logger.info('CONNECTION', `Connection removed: ${id}`, { success: result })

    return result
  }

  getAllConnections() {
    return Array.from(this.connections.values()).map(conn => ({
      id: conn.id,
      config: conn.config
    }))
  }

  async getDatabases() {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }
    
    const { queryType, url, token, username, password } = this.currentConnection.config
    
    if (queryType === 'influxql') {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }
      
      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }
      
      const response = await axios.get(`${url}/query`, {
        params: { q: 'SHOW DATABASES' },
        headers,
        ...authConfig
      })
      
      if (response.data && response.data.results && response.data.results[0].series) {
        const databases = response.data.results[0].series[0].values.map(v => v[0])
        // Filter out system databases if needed
        return databases.filter(db => db !== '_internal')
      }
    } else {
      // For Flux, return buckets as databases
      const query = 'buckets()'
      const results = await this.executeFluxQuery(this.currentConnection.queryApi, query)
      return results.map(r => r.name)
    }
    
    return []
  }

  async getMeasurementsForDatabase(database) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }
    
    const { queryType, url, token, username, password } = this.currentConnection.config
    
    if (queryType === 'influxql') {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }
      
      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }
      
      const response = await axios.get(`${url}/query`, {
        params: { 
          q: 'SHOW MEASUREMENTS',
          db: database
        },
        headers,
        ...authConfig
      })
      
      if (response.data && response.data.results && response.data.results[0].series) {
        return response.data.results[0].series[0].values.map(v => v[0])
      }
    } else {
      // For Flux, use the schema API
      const query = `
        import "influxdata/influxdb/schema"
        schema.measurements(bucket: "${database}")
      `
      const results = await this.executeFluxQuery(this.currentConnection.queryApi, query)
      return results.map(r => r._value)
    }
    
    return []
  }

  async executeQueryForDatabase(query, database) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }
    
    const { queryType } = this.currentConnection.config
    
    if (queryType === 'influxql') {
      return await this.executeInfluxQLQuery(query, database)
    } else {
      return await this.executeFluxQuery(this.currentConnection.queryApi, query)
    }
  }

  async getServerInfo() {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    const perfId = `server_info_${Date.now()}`
    logger.startPerformance(perfId)
    logger.debug('SERVER', 'Fetching server info')

    const { id, url, token, username, password } = this.currentConnection.config

    // 检查缓存
    const cacheKey = this._getCacheKey('serverInfo', { connectionId: id })
    const cachedResult = this._getFromCache(cacheKey)
    if (cachedResult) {
      logger.endPerformance(perfId, { source: 'cache' })
      return cachedResult
    }

    try {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }

      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }

      const axiosInstance = this._getAxiosInstance(id, url)

      // Get version from ping endpoint
      const pingResponse = await axiosInstance.head('/ping', {
        headers,
        ...authConfig
      })

      const version = pingResponse.headers['x-influxdb-version'] || 'Unknown'
      const build = pingResponse.headers['x-influxdb-build'] || 'Unknown'

      // Try to get more info via query
      let uptimeInfo = null
      let memoryInfo = null

      try {
        // Get diagnostics info (may not be available in all versions)
        const diagnosticsResponse = await axiosInstance.get('/query', {
          params: { q: 'SHOW DIAGNOSTICS' },
          headers,
          ...authConfig
        })

        if (diagnosticsResponse.data && diagnosticsResponse.data.results) {
          const results = diagnosticsResponse.data.results[0]
          if (results && results.series) {
            results.series.forEach(serie => {
              if (serie.name === 'system') {
                const values = serie.values[0]
                const columns = serie.columns
                const uptimeIndex = columns.indexOf('uptime')
                if (uptimeIndex !== -1) {
                  uptimeInfo = values[uptimeIndex]
                }
              }
            })
          }
        }
      } catch (e) {
        logger.debug('SERVER', 'Could not get diagnostics info', { error: e.message })
      }

      // Get stats info
      try {
        const statsResponse = await axiosInstance.get('/query', {
          params: { q: 'SHOW STATS' },
          headers,
          ...authConfig
        })

        if (statsResponse.data && statsResponse.data.results) {
          const results = statsResponse.data.results[0]
          if (results && results.series) {
            results.series.forEach(serie => {
              if (serie.name === 'runtime') {
                const values = serie.values[0]
                const columns = serie.columns
                const allocIndex = columns.indexOf('Alloc')
                const sysIndex = columns.indexOf('Sys')
                if (allocIndex !== -1 && sysIndex !== -1) {
                  memoryInfo = {
                    alloc: values[allocIndex],
                    sys: values[sysIndex]
                  }
                }
              }
            })
          }
        }
      } catch (e) {
        logger.debug('SERVER', 'Could not get stats info', { error: e.message })
      }

      const serverInfo = {
        version,
        build,
        uptime: uptimeInfo,
        memory: memoryInfo
      }

      // 缓存服务器信息（较长的缓存时间）
      this._saveToCache(cacheKey, serverInfo)
      logger.endPerformance(perfId, { version, build })
      logger.info('SERVER', 'Server info retrieved', serverInfo)

      return serverInfo
    } catch (error) {
      logger.endPerformance(perfId, { error: true })
      logger.error('SERVER', 'Failed to get server info', error)
      return {
        version: 'Unknown',
        build: 'Unknown',
        uptime: null,
        memory: null
      }
    }
  }

  async createDatabase(databaseName) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    logger.info('DATABASE', `Creating database: ${databaseName}`)
    const { id, url, token, username, password } = this.currentConnection.config

    try {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }

      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }

      const axiosInstance = this._getAxiosInstance(id, url)
      const response = await axiosInstance.post('/query', null, {
        params: { q: `CREATE DATABASE "${databaseName}"` },
        headers,
        ...authConfig
      })

      if (response.data && response.data.results) {
        const result = response.data.results[0]
        if (result.error) {
          throw new Error(result.error)
        }

        // 清除数据库列表缓存
        this._clearConnectionCache(id)
        logger.info('DATABASE', `Database created successfully: ${databaseName}`)
        return true
      }

      return false
    } catch (error) {
      logger.error('DATABASE', `Failed to create database: ${databaseName}`, error)
      throw error
    }
  }

  async deleteDatabase(databaseName) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    logger.warn('DATABASE', `Deleting database: ${databaseName}`)
    const { id, url, token, username, password } = this.currentConnection.config

    try {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }

      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }

      const axiosInstance = this._getAxiosInstance(id, url)
      const response = await axiosInstance.post('/query', null, {
        params: { q: `DROP DATABASE "${databaseName}"` },
        headers,
        ...authConfig
      })

      if (response.data && response.data.results) {
        const result = response.data.results[0]
        if (result.error) {
          throw new Error(result.error)
        }

        // 清除相关缓存
        this._clearConnectionCache(id)
        logger.info('DATABASE', `Database deleted successfully: ${databaseName}`)
        return true
      }

      return false
    } catch (error) {
      logger.error('DATABASE', `Failed to delete database: ${databaseName}`, error)
      throw error
    }
  }

  async deleteMeasurement(database, measurement) {
    if (!this.currentConnection) {
      throw new Error('No connection selected')
    }

    logger.warn('MEASUREMENT', `Deleting measurement: ${measurement} from database: ${database}`)
    const { id, url, token, username, password } = this.currentConnection.config

    try {
      const headers = {}
      if (token) {
        headers['Authorization'] = `Token ${token}`
      }

      const authConfig = {}
      if (username && password) {
        authConfig.auth = { username, password }
      }

      const axiosInstance = this._getAxiosInstance(id, url)
      const response = await axiosInstance.post('/query', null, {
        params: {
          db: database,
          q: `DROP MEASUREMENT "${measurement}"`
        },
        headers,
        ...authConfig
      })

      if (response.data && response.data.results) {
        const result = response.data.results[0]
        if (result.error) {
          throw new Error(result.error)
        }

        // 清除相关缓存
        this._clearConnectionCache(id)
        logger.info('MEASUREMENT', `Measurement deleted successfully: ${measurement}`)
        return true
      }

      return false
    } catch (error) {
      logger.error('MEASUREMENT', `Failed to delete measurement: ${measurement}`, error)
      throw error
    }
  }
}

export default new InfluxDBService()